package com.kantboot.system.user.service.impl;

import com.kantboot.system.user.dao.repository.entity.SysUserRepository;
import com.kantboot.system.user.domain.entity.SysUser;
import com.kantboot.system.user.service.ISysUserRoleService;
import com.kantboot.system.user.service.ISysUserService;
import com.kantboot.system.user.setting.SystemUserSetting;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl implements ISysUserService {

    @Resource
    private SysUserRepository repository;

    @Resource
    private ISysUserRoleService userRoleService;

    @Resource
    private SystemUserSetting setting;


    @Override
    public SysUser createNewUser(SysUser user) {
        if(user==null){
            user = new SysUser();
        }
        user.setId(null);
        user.setIsInit(false);
        user.setIsTemporary(true);
        SysUser save = repository.save(user);
        // 生成直属码，直属码是用户id的32进制表示
        save.setDirectCode(Long.toString(save.getId(),32));
        save=repository.save(save);

        userRoleService.addUserRole(save.getId(),setting.getDefaultRoleCode());
        return repository.findById(save.getId()).orElseThrow();
    }

    @Override
    public List<SysUser> getByRoleCode(String roleCode) {
        return repository.findByRoleCode(roleCode);
    }

    @Override
    public List<SysUser> getByRoleCodeAndInviterId(String roleCode, Long inviterId) {
        return repository.findByRoleCodeAndInviterId(roleCode,inviterId);
    }

    @Override
    public Long countByRoleCodeAndInviterId(String roleCode, Long inviterId) {
        return repository.countByRoleCodeAndInviterId(roleCode,inviterId);
    }

    @Override
    public List<SysUser> getByInviteUserId(Long inviterUserId) {
        return repository.findByInviteUserId(inviterUserId);
    }

    @Override
    public List<SysUser> getAll() {
        return repository.findAll();
    }

    @Override
    public SysUser getById(Long id) {
        return repository.findById(id).orElse(null);
    }
}
